/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Util;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringEscapeUtils;
import org.json.JSONException;
import org.json.JSONObject;
import th.co.tac.esv.tel.ejb.dat.tpt.OutputTemplate;

/**
 *
 * @author Peat
 */
public class TranslatorUtils {

    public static JSONObject toJSON(Exception e) throws JSONException {
        JSONObject result = new JSONObject();
        result.put("exceptionName", e.getClass());
        result.put("exceptionMsg", e.getMessage());
        result.put("stacktrace", getStackTrace(e));
        return result;
    }

    /**
     * This function will implement case by case.
     *
     * @param o
     * @return
     * @throws JSONException
     */
    public static JSONObject toJSON(OutputTemplate o) throws JSONException {
        return null;
    }
    
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        t.printStackTrace(pw);
        return sw.toString();
    }

    public static String getBackendLang(HttpServletRequest request) {
        String lang = (String) request.getSession().getAttribute("LANGS");
        if (lang.equals("th")) {
            return "T";
        } else if (lang.equals("en")) {
            return "E";
        } else {
            return lang;
        }
    }

    public static String oneEscape(String ascii) {
        StringBuffer unicode = new StringBuffer(ascii);
        int code;
        for (int i = 0; i < ascii.length(); i++) {
            code = (int) ascii.charAt(i);
            if ((0xA1 <= code) && (code <= 0xFB)) {
                unicode.setCharAt(i, (char) (code + 0xD60));
            }
        }
        return StringEscapeUtils.escapeHtml(unicode.toString());
    }
    
    public static String toServerPhoneNumber(String s) {
        if (s.startsWith("66")) {
            return s;
        } else if (s.startsWith("0")) {
            return "66" + s.substring(1);
        } else {
            return s;
        }
    }

    public static String toUIPhoneNumber(String s) {
        if (s.startsWith("66")) {
            return "0" + s.substring(2);
        } else if (s.startsWith("0")) {
            return s;
        } else {
            return s;
        }
    }
}
